<template>
    <div class="container">
        <!-- 页面标题 -->
        <div class="header">
            <h2>物业联系人管理</h2>
            <p class="description">在这里查询、编辑或删除物业联系人信息。</p>
        </div>

        <!-- 搜索框 -->
        <div class="search-container">
            <el-input v-model="searchQuery" placeholder="请输入联系人姓名、联系电话或小区ID进行搜索" clearable prefix-icon="el-icon-search"
                class="search-input" />
        </div>

        <!-- 表格 -->
        <el-table :data="paginatedData" border style="margin-top: 20px;">
            <el-table-column prop="owner_id" label="ID" width="100"></el-table-column>
            <el-table-column prop="name" label="联系人"></el-table-column>
            <el-table-column prop="unit_id" label="小区ID" width="180"></el-table-column>
            <el-table-column prop="phone" label="联系电话" width="200"></el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-if="filteredData.length > 0" background layout="prev, pager, next, jumper"
            :total="filteredData.length" :page-size="pageSize" :current-page="currentPage"
            @current-change="handlePageChange" />

        <!-- 编辑模态框 -->
        <el-dialog v-model="editDialogVisible" title="编辑联系人信息">
            <el-form :model="currentEdit" label-width="80px">
                <el-form-item label="姓名">
                    <el-input v-model="currentEdit.name" />
                </el-form-item>
                <el-form-item label="小区ID">
                    <el-input v-model="currentEdit.unit_id" />
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="currentEdit.phone" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">保存</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

export default {
    setup() {
        const owner = ref([]); // 存储联系人信息
        const currentPage = ref(1); // 当前页
        const pageSize = ref(10); // 每页条数
        const searchQuery = ref(''); // 搜索查询

        const editDialogVisible = ref(false); // 编辑框的显示状态
        const currentEdit = ref({}); // 当前编辑的数据

        // 搜索过滤
        const filteredData = computed(() => {
            const lowerQuery = searchQuery.value.toLowerCase();
            return owner.value.filter(
                (item) =>
                    item.name.toLowerCase().includes(lowerQuery) ||
                    item.phone.includes(lowerQuery) ||
                    item.unit_id.toString().includes(lowerQuery) ||
                    item.owner_id.toString().includes(lowerQuery)
            );
        });

        // 分页数据
        const paginatedData = computed(() => {
            const start = (currentPage.value - 1) * pageSize.value;
            const end = start + pageSize.value;
            return filteredData.value.slice(start, end);
        });

        onMounted(() => {
            fetchData();
        });

        // 获取联系人数据
        const fetchData = async () => {
            const token = localStorage.getItem('token');
            if (!token) {
                alert('Token无效，请重新登录');
                return;
            }

            try {
                const response = await axios.get('http://localhost:3008/ownerList', {
                    headers: {
                        Authorization: `Bearer ${token}`,
                    },
                });
                if (response.data && response.data.data) {
                    owner.value = response.data.data;
                } else {
                    alert('没有找到联系人数据');
                }
            } catch (error) {
                console.log('获取数据失败', error);
                alert('服务器错误，无法获取联系人数据');
            }
        };

        // 分页处理
        const handlePageChange = (page) => {
            currentPage.value = page;
        };

        // 编辑联系人
        const handleEdit = (row) => {
            console.log('编辑行数据：', row); // 添加调试信息，查看是否进入该函数
            currentEdit.value = { ...row }; // 确保数据复制正确
            editDialogVisible.value = true;
        };

        // 保存编辑
        const saveEdit = async () => {
            try {
                const response = await axios.put(`http://localhost:3008/owner/${currentEdit.value.owner_id}`, currentEdit.value, {
                    headers: {
                        Authorization: `Bearer ${localStorage.getItem('token')}`,
                    },
                });
                if (response.status === 200) {
                    const index = owner.value.findIndex((item) => item.owner_id === currentEdit.value.owner_id);
                    if (index !== -1) {
                        owner.value[index] = { ...currentEdit.value }; // 更新本地数据
                    }
                    editDialogVisible.value = false;
                }
            } catch (error) {
                console.log('编辑失败', error);
                alert('编辑联系人失败');
            }
        };

        // 删除联系人
        const handleDelete = async (row) => {
            if (confirm(`确定删除联系人 ${row.name} 吗？`)) {
                try {
                    const response = await axios.delete(`http://localhost:3008/owner/${row.owner_id}`, {
                        headers: {
                            Authorization: `Bearer ${localStorage.getItem('token')}`,
                        },
                    });
                    if (response.status === 200) {
                        owner.value = owner.value.filter((item) => item.owner_id !== row.owner_id);
                        alert('删除成功');
                    }
                } catch (error) {
                    console.log('删除失败', error);
                    alert('删除联系人失败');
                }
            }
        };

        return {
            owner,
            filteredData,
            paginatedData,
            currentPage,
            pageSize,
            searchQuery,
            handlePageChange,
            handleEdit,
            handleDelete,
            editDialogVisible,
            currentEdit,
            saveEdit,
        };
    },
};
</script>

<style>
/* 页面容器 */
.container {
    width: 100%;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 页面标题 */
.header {
    text-align: center;
    margin-bottom: 20px;
}

.header h2 {
    font-size: 24px;
    color: #333;
    margin-bottom: 8px;
}

.header .description {
    font-size: 14px;
    color: #666;
}

/* 搜索框 */
.search-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
}

.search-input {
    max-width: 500px;
    width: 100%;
}

/* 表格 */
.el-table {
    background-color: white;
    border-radius: 8px;
}

/* 分页 */
.el-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

/* 底部提示 */
.footer {
    margin-top: 20px;
    text-align: center;
    font-size: 14px;
    color: #666;
}
</style>
